import {RouteReuseStrategy, DetachedRouteHandle, ActivatedRouteSnapshot} from '@angular/router';

export class RebirthRouterReuseStrategy implements RouteReuseStrategy {


  handlers: { [key: string]: DetachedRouteHandle } = {};

  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    // console.log('5')
    return this.isReusable(route);
  }

  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
    // console.log('4')
    // console.warn(!!handle)
    !!handle && (this.handlers[route.url.join("/") || route.parent.url.join("/")] = handle);
  }

  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    // console.log('3')
    // console.log(`shouldAttach: ${!!route.routeConfig} `)
    // console.log(`shouldAttach: ${route.routeConfig} `)
    return !!route.routeConfig && !!this.handlers[route.url.join("/") || route.parent.url.join("/")];
  }

  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
    // console.log('2')
    // console.log(this.handlers)

    if (!route.routeConfig) {return null; };
    if (route.routeConfig.loadChildren) {return null; };
    return this.isReusable(route) && (route.routeConfig ? this.handlers[route.url.join("/") || route.parent.url.join("/")] : null);
  }

  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    // console.log('1')
    return future.routeConfig === curr.routeConfig && this.isReusable(future);
  }

  private isReusable(route: ActivatedRouteSnapshot) {
    return route.data && (route.data['reusable'] !== void 0);
  }

}
